package middleware

import (
	"bytes"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"robotDaBai/public"
	"time"
)

// 请求进入日志记录
func requestInlog(this *gin.Context){
	traceContext := lib.NewTrace()
	//从上下文中 获取 traceId 和 spanId
	if traceId:=this.Request.Header.Get("com-header-rid");traceId!=""{
		traceContext.TraceId = traceId
	}
	if spanId := this.Request.Header.Get("com-header-spanid");spanId!=""{
		traceContext.SpanId = spanId
	}

	this.Set("startExecTime",time.Now())
	this.Set("trace",traceContext)

	//得到请求参数
	bodyBytes,_ := ioutil.ReadAll(this.Request.Body)
	this.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

	//日志输出
	lib.Log.TagInfo(traceContext,"_com_request_in",map[string]interface{}{
		"uri":this.Request.RequestURI,
		"method":this.Request.Method,
		"args":this.Request.PostForm,
		"body":string(bodyBytes),
		"from":this.ClientIP(),
	})
}

func requestOutLog(this *gin.Context){
	endExecTime := time.Now()

	response,_:=this.Get("response")
	st,_:=this.Get("startExecTime")
	startExecTime,_:=st.(time.Time)

	//输出退出日志
	public.ComLogNotice(this,"_com_request_out",map[string]interface{}{
		"uri":       this.Request.RequestURI,//请求url
		"method":    this.Request.Method,//请求类型
		"args":      this.Request.PostForm,//post 请求数据
		"from":      this.ClientIP(),//请求ip
		"response":  response,//程序的响应内容
		"proc_time": endExecTime.Sub(startExecTime).Seconds(),//程序执行的时间
	})
}

//日志中间件
func RequestLog() gin.HandlerFunc{
	return func(this *gin.Context) {
		requestInlog(this)
		defer requestOutLog(this)
		this.Next()
	}
}